package com.glory.hikvisionmobile.activity;

import android.Manifest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.glory.hikvisionmobile.BuildConfig;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.Login.LoginInfoBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_PasswordEditText;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends FreeUI_BaseActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.ivSetting)
    ImageView ivSetting;
    @BindView(R.id.tvVersion)
    TextView tvVersion;
    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;
    @BindView(R.id.etPassword)
    FreeUI_PasswordEditText etPassword;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.rlParent)
    RelativeLayout rlParent;

    private static final int PERMISSIONS_REQUEST_CODE = 10;
    private int code;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        tvVersion.setText(FreeApi_Utils.getVerName());
        String userName = FreeApi_SharePreferencesUtils.getSharePre("HIK_VISION_FILE", "CURRENT_USER", getApplicationContext());
        etUser.setText(userName);
        FreeApi_ActivityManager.getActivityManager().addActivity(this);
    }

    @Override
    protected void initData() {
        requestPermission();
        detectionUpdate(true);
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }


    @OnClick({R.id.btnLogin,R.id.ivSetting})
    public void onViewClicked(View v) {
        switch (v.getId()){
            case R.id.btnLogin:
                if (etUser.getText().toString().trim().length() == 0){
                    showToast("请输入用户名",false);
                    return;
                }

                if (etPassword.getText().toString().trim().length() == 0){
                    showToast("请输入密码",false);
                    return;
                }

//                detectionUpdate(false);
                login();
                break;
            case R.id.ivSetting:
                FreeApi_Utils.skipWithExtraIntent("header", LoginActivity.this, SettingActivity.class);
                break;
        }
    }

    private void login() {
        JsonObject map = new JsonObject();
        map.addProperty("userName",etUser.getText().toString().trim());
        map.addProperty("password",etPassword.getText().toString().trim());
        map.addProperty("actionType","Login");
        NetUtils.requestDara("HIK.PdaLogin",this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<LoginInfoBean>>(
                new TypeToken<BaseResponseBean<LoginInfoBean>>() {
                }.getType(), getSupportFragmentManager(), this){

            @Override
            public void onSuccess(Response<BaseResponseBean<LoginInfoBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())) {
                    Constant.LOGIN_BEAN = response.body().getBody();
                    Constant.CURRENT_USER = etUser.getText().toString().trim();
                    Constant.CURRENT_PASSWORD = etPassword.getText().toString().trim();
                    if (Constant.LOGIN_BEAN.getAuthoritys().size() <= 0){
                        showToast("您已登陆成功，但是无任何权限",false);
                        return;
                    }
                    FreeApi_SharePreferencesUtils.setSharePre("HIK_VISION_FILE", "CURRENT_USER", etUser.getText().toString().trim(), getApplicationContext());
                    showToast("登陆成功", true);
                    FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, HomeActivity.class);
                    finish();

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LoginInfoBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLogin");
            }
        });

//        String ss = "{\n" +
//                "\t\"Header\": {\n" +
//                "\t\t\"TRANSACTIONID\": \"c5e5e318-389d-4c39-b914-e4c10ba519d4\",\n" +
//                "\t\t\"RESULT\": \"SUCCESS\"\n" +
//                "\t},\n" +
//                "\t\"Body\": {\n" +
//                "\t\t\"authoritys\": [{\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_LotScrapCancelActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_CheckPlanFromActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_IQPCRecordActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"DialogActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_TrackInActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_GraphiteBoatTrackOutActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"TrackOut;TrackExit;Add;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAEqpFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Eqp_EqpCheckActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_SPCDataCollectActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;TemporarySave;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_GraphiteBoatTrackInActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_DataCollectActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Search;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_LotScrapActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_BindCarrierActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_ReplaceRecordActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_SearchWorkThingActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Search;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_LotGoActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_AddDrugRecordActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAEqpFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Eqp_EqpKeepDetailsActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_LotSplitActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_TrackOutActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Scrap;TrackExit;SPCDataCollect;TrackOut;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_MaterielRecordActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_LotPauseActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_PatchTrackOutActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"TrackOut;DieBond;TrackExit;BindCarrier;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_LotBackStepActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_FromSearchActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"NewBuild;Search;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_LotAddActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;Refresh;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_ChangeShiftsActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAEqpFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Eqp_EqpKeepActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Search;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_ProcessSheetActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Search;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_SortingTrackOutActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"TrackOut;TrackExit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAFormFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"From_CheckPlanActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Search;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_MapPingActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Submit;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDAWorkFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Work_EqpWorkActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Search;\"\n" +
//                "\t\t}, {\n" +
//                "\t\t\t\"tabKey\": \"PDALotFragment\",\n" +
//                "\t\t\t\"funcitonKey\": \"Lot_SearchDieActivity\",\n" +
//                "\t\t\t\"buttonKey\": \"Refresh;Submit;\"\n" +
//                "\t\t}],\n" +
//                "\t\t\"userName\": \"pda\",\n" +
//                "\t\t\"desription\": \"pda\"\n" +
//                "\t}\n" +
//                "}";
//        Constant.CURRENT_USER = etUser.getText().toString().trim();
//        Constant.CURRENT_PASSWORD = etPassword.getText().toString().trim();
//        BaseResponseBean<LoginInfoBean> data = (new Gson()).fromJson(ss, new TypeToken<BaseResponseBean<LoginInfoBean>>() {}.getType());
//        Constant.LOGIN_BEAN = data.getBody();
//        FreeApi_SharePreferencesUtils.setSharePre("HIK_VISION_FILE", "CURRENT_USER", etUser.getText().toString().trim(), getApplicationContext());
//        FreeApi_SharePreferencesUtils.setSharePre("HIK_VISION_FILE", "CURRENT_PASSWORD", etPassword.getText().toString().trim(), getApplicationContext());
//        FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, Work_MapPingActivity.class);
//        finish();
    }

    private void detectionUpdate(boolean isInstand)
    {
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        FreeUI_EntityCallBack<FreeUI_VersionEntity> callBack = new FreeUI_EntityCallBack<FreeUI_VersionEntity>
                (new TypeToken<FreeUI_VersionEntity>() {
                }.getType()) {

            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity entity = response.body();
                entity.setCurrentVersion(version);
                code = FreeApi_Utils.compareVersion(version,entity.getVersion());
                if(code == -1) {
                    FreeUI_DownloadFragmentDialog downloadFragmentDialog = new FreeUI_DownloadFragmentDialog();
                    downloadFragmentDialog.setData(entity);
                    downloadFragmentDialog.show(getSupportFragmentManager(),"DOWNLOAD");
                }

                if (!isInstand & code != -1){
                    login();
                }
            }

            @Override
            public void onError
                    (Response<FreeUI_VersionEntity> response) {
                super.onError(response);
            }
        };
        Map<String, String> map = new HashMap<>();
        FreeApi_NetUtils.requestGetNet(BuildConfig.DEBUG ? Constant.FILE_URL_DEBUG : Constant.FILE_URL, this, map, callBack);
    }

    @AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
    private void requestPermission(){
        String[] perms = {Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE};
        //权限判断，第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(this, perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...
            //login();
        }else {
            //没有权限的话，先提示，点确定后弹出系统的授权提示框
            EasyPermissions.requestPermissions(this, "程序运行需要权限",
                    PERMISSIONS_REQUEST_CODE, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        showToast("用户授权失败",false);
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

}
